var AppUtils = function(){
	function getCheckedRowsId(gridObj){
		try{
			var records = gridObj.getCheckedRowsRecords();
			var ids = new Array();
			$.each(records,function(i,k){
				ids.push(k["id"]);
			});
			return ids;
		}catch(error){
			return null;
		}
		
	}
	function _exportExcel(gridObjId){
		var gridObj = $.fn.bsgrid.getGridObj(gridObjId);
		$("#exportExcelForm").remove();
		var formHtml = '<form name="exportExcelForm" id="exportExcelForm">';
		//导出标记
		formHtml += '<input type="hidden" name="app_exportDataType" value="excel">';
		var ids = getCheckedRowsId(gridObj);
		if (ids && ids.length > 0) {
			formHtml += '<input type="hidden" name="app_exportIds" value="' + ids + '">';
		}
		var colModel = gridObj.getGridHeaderObject();
		for(var i=0;i<colModel.length;i++){
			var colObj = $(colModel[i]);
			var headerName = $.trim(colObj.text());
			var columnName = colObj.attr("w_index"); 
			if(headerName && columnName){
				formHtml += '<input type="hidden" name="app_exportHeaderName" value="' + headerName + '"/>';
				formHtml += '<input type="hidden" name="app_exportColumnName" value="' + columnName + '"/>';
			}
		}
		
		var pageCondition = gridObj.getPageCondition(0);
		var condition = pageCondition.split('&');
		$.each(condition,function(index,element){
			var name = element.split('=')[0];
			if(name == 'curPage'){
				formHtml += '<input type="hidden" name="' + name + '" value="' + 0 + '">';
			}else if(name == 'pageSize'){
				formHtml += '<input type="hidden" name="' + name + '" value="' + 10000000 + '">';
			}else{
				formHtml += '<input type="hidden" name="' + name + '" value="' + element.split('=')[1] + '">';
			}
		});
		formHtml += '</form>';
		$('body').append(formHtml);
		document.exportExcelForm.action = gridObj.options.settings.url;
		document.exportExcelForm.target = '_top';
		document.exportExcelForm.method = 'post';
		document.exportExcelForm.submit();
		
		
		
	}
	
	return {
		// cookie操作
		cookie:function(name, value, options) {
		    if (typeof value != 'undefined') { // name and value given, set cookie
		        options = options || {};
		        if (value === null) {
		            value = '';
		            options.expires = -1;
		        }
		        var expires = '';
		        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
		            var date;
		            if (typeof options.expires == 'number') {
		                date = new Date();
		                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
		            } else {
		                date = options.expires;
		            }
		            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		        }
		        var path = options.path ? '; path=' + options.path : '';
		        var domain = options.domain ? '; domain=' + options.domain : '';
		        var secure = options.secure ? '; secure' : '';
		        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
		    } else { // only name given, get cookie
		        var cookieValue = null;
		        if (document.cookie && document.cookie != '') {
		            var cookies = document.cookie.split(';');
		            for (var i = 0; i < cookies.length; i++) {
		                var cookie = jQuery.trim(cookies[i]);
		                // Does this cookie string begin with the name we want?
		                if (cookie.substring(0, name.length + 1) == (name + '=')) {
		                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
		                    break;
		                }
		            }
		        }
		        return cookieValue;
		    }
		},
		//获取窗体高度
		getScreenHeight : function(doc) {
			if(!doc) {
				doc = document;
			}
			var bdy = (doc.documentElement && doc.documentElement.clientWidth)?doc.documentElement:doc.body;
			return bdy.clientHeight;
		},
		//添加时间戳
		date2Url : function(url) {
			if(url.indexOf('?') >= 0) {
				return url + "&time=" + new Date().getTime();
			}else{
				return url + "?time=" + new Date().getTime();
			}
		},
		// 添加TAB页面
		addTabPage:function (title, url, closeable, $this, refresh){
			top.$.fn.jerichoTab.addTab({
		        tabFirer: $this,
		        title: $.trim(title),
		        closeable: closeable == undefined,
		        data: {
		            dataType: 'iframe',
		            dataLink: url
		        }
		    }).loadData(refresh != undefined);
		},
		validatorRemoteCache:function(ck){
			if(typeof ck == 'string') {
				ck = jQuery(ck);
			}
			ck.removeData("previousValue");
		},
		/**
		 * 判断checkbox是否选中
 		 * @param {Object} ck，可以是object或者jquery selector字符串
		 */
		isChecked: function(ck) {
			if(typeof ck == 'string') {
				ck = jQuery(ck);
			}
			return ck.prop('checked');
		},
		setChecked:function(ck) {
			if(typeof ck == 'string') {
				ck = jQuery(ck);
			}
			
			ck.prop('checked', true);
		},
		//清除表单
		clearForm:function (objE){//objE为form表单 
			if(typeof objE == 'string') {
				objE = $(objE);
			}
			objE.find(':input').each(  
	            function(){  
	                switch(this.type){  
	                    case 'password':  
	                    case 'select-multiple':  
	                    case 'select-one':  
	                    case 'text':
	                    case 'hidden':	
	                    case 'textarea':  
	                        $(this).val('');  
	                        break;  
	                    case 'checkbox':  
	                    case 'radio':  
	                        this.checked = false;  
	                }  
	            }     
	        ); 
	        
			objE.find('label.error').each(  
	                function(){  
	                    $(this).remove();
	                }     
	            ); 
	    },
	    //获取grid选择的选择框
	    gridCheckColumnValue:function(gridObj,column){
	    	var rowsIndex = gridObj.getCheckedRowsIndexs();
	    	var array = new Array();
	    	$.each(rowsIndex,function(){
	    		array.push(gridObj.getColumnValue(this, column));
	    	});
	    	return array;
	    },
	    dateCompare:function(beginTime, endTime) {
	        var starttime = new Date(beginTime);
	        var lktime = new Date(endTime);

	        if (starttime.getTime() > lktime.getTime()) {
	            return false;
	        }
	        else
	            return true;
	    },
	    dateSubtract:function(beginTime, endTime){
	    	 var starttime = new Date(beginTime);
		     var lktime = new Date(endTime);
		     return lktime.getTime()-starttime.getTime();
	    },
	    gridFormatterScrq:function(record, rowIndex, colIndex, options){
			return record['scrq'].length>19?record['scrq'].substring(0,19):record['scrq'];
		},
		bsgridExportButton:function(options){
			if($("#exportExcelButton").length ==0){
				var buttonHtml = '<td id="exportExcelButton">';
		        buttonHtml += '<table class="bsgrid_pulgin_table"><tr>';
		        buttonHtml += '<td><input onclick="AppUtils.exportExcel(\''+options.gridId+'\')" class="bsgrid_icon icon_view" type="button" value="导出"/></td>';
		        buttonHtml += '</tr></table>';
		        buttonHtml += '</td>';
		        $('#' + options.pagingOutTabId + ' tr:eq(0)').prepend(buttonHtml);
			}
		},
		loadJsonData:function(url,data,callback){
			$.ajax({
				  url: url,
				  data: data,
				  type:"post",
				  success: callback,
				  dataType: "json"
				});
		},
		exportExcel:function(gridObjId){
			var gridObj = $.fn.bsgrid.getGridObj(gridObjId);
			var ids = null;
			try{
				ids = gridObj.getCheckedRowsIndexs();
			}catch(error){}
			var all = gridObj.getTotalRows();
			if(ids && ids.length >0){
				_exportExcel(gridObjId);
			}else if(all == 0){
				Message.alert("列表中没有数据，无法导出！");
			}else{
				Message.confirm("确认导出列表中的所有数据吗？",function(index){
					_exportExcel(gridObjId);
					layer.close(index);
				});
			}
		}

		
	}
}();